package org.soarsky.wealthchengdu.google.map;



import org.soarsky.wealthchengdu.R;
import org.soarsky.wealthchengdu.entity.MapSearchData;
import org.soarsky.wealthchengdu.google.map.BaiduLocation.IGetLocation;
import org.soarsky.wealthchengdu.network.ParserMapResults;
import org.soarsky.wealthchengdu.util.Config;
import org.soarsky.wealthchengdu.view.LoadingDialog;

import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;


import com.baidu.location.BDLocation;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;

public class GoogleMapActivity extends MapActivity {
	private static GoogleMapActivity sMe = null;
	private static final String TAG="GoogleMapActivity";
	private static final int MIN_DISTANCE=800;//查询的最小距离 
	private static final int MAX_DISTANCE=1000;//查询的最大距离
	private MapView mMapView;
	private AbstractGoogleMap mMapController = null;
	private Button mLocationButton = null;
	private LocationOperator mLocationOperator = null;
	private ParserMapResults mapResults ;
	private MapActivityContor mapActivityContor;
	private MarkOPertorAssistant markOPertorAssistant;
	private BaiduLocation mBaiduLocation = null;
	private LoadingDialog loadingDialog = null;
	private MapOption mMapOption = null;
	public static boolean click = false;
	public static int status = -1;
	
	//会议指南
	public void openMeetingMap(){
		// 30.6497110116642,104.066224917725 索菲特万达
		// 30.6750701847006,104.004041925034 香格里拉
		mMapView.setBuiltInZoomControls(false);
		mMapController.clearLines();
		mMapController.clearMarks();
		MarkPoint markPoint1 =  new MarkPoint(0,30.6497110116642,104.066224917725, null);
		markPoint1.setTitle(getResources().getString(R.string.map_assembly_room_one));
		//markPoint1.setContent("锦江区滨江中路15号");
		markOperator.addMarkOverlay(markPoint1);
		MarkPoint markPoint2 = new MarkPoint(1,30.6750701847006,104.004041925034, null);
		markPoint2.setTitle(getResources().getString(R.string.map_assembly_room_two));
		//markPoint2.setContent("锦江区滨江东路9号");
		markOperator.addMarkOverlay(markPoint2);
	}
	//查找美食
	public void openFood(){
		mMapController.clearLines();
		mMapController.clearMarks();
		MapSearchData mapSearchData = null;
		StringBuilder builder = new StringBuilder();
		if(getLocation()==null){
			logE("Location is null");
			return;
		}
		builder.append(getLocation().getLatitude());
		builder.append(",");
		builder.append(getLocation().getLongitude());
		logE(builder.toString());
		try {
			mapSearchData = mapResults.getSearchResult(builder.toString(),MIN_DISTANCE, true,ParserMapResults.FOOD,getLanguage());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(mapSearchData==null){
			logE("not find food");
		}else{
			markOPertorAssistant.startDraw(mapSearchData);
		}
	}
	//查找酒店
	public void openWineshop(){
		mMapController.clearLines();
		mMapController.clearMarks();
		MapSearchData mapSearchData = null;
		StringBuilder builder = new StringBuilder();
		if(getLocation()==null){
			logE("Location is null");
			return;
		}
		builder.append(getLocation().getLatitude());
		builder.append(",");
		builder.append(getLocation().getLongitude());
	
		
		try {
			mapSearchData = mapResults.getSearchResult(builder.toString(), MIN_DISTANCE, true,ParserMapResults.LODGING,getLanguage());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(mapSearchData==null){
			logE("not find Wineshop");
		}else{
			markOPertorAssistant.startDraw(mapSearchData);
		}
	}
	
	//查找景点
		public void openTravel(){
			mMapController.clearLines();
			mMapController.clearMarks();
			MapSearchData mapSearchData = null;
			//StringBuilder builder = new StringBuilder();
			if(getLocation()==null){
				logE("Location is null");
				return;
			}
			//point_of_interest
			//30.6497110116642,104.066224917725
			//-33.8670522,151.1957362
			
			StringBuilder builder2 = new StringBuilder();
			builder2.append("museum");
			builder2.append("%7C");
			builder2.append("amusement_park");
			builder2.append("%7C");
			builder2.append("park");
			builder2.append("%7C");
			builder2.append("aquarium");
			builder2.append("%7C");
			builder2.append("zoo");
			//Log.e("test", "builder="+builder.toString());
			try {
				mapSearchData = mapResults.getSearchResult("30.67,104.06", 150000, true,builder2.toString(),getLanguage());
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(mapSearchData==null){
				logE("not find Wineshop");
			}else{
				markOPertorAssistant.startDraw(mapSearchData);
			}
		}
	//交通
	public void openTraffic(){
		mMapController.clearLines();
		mMapController.clearMarks();
		MapSearchData mapSearchData = null;
		StringBuilder builder = new StringBuilder();
		if(getLocation()==null){
			logE("Location is null");
			return;
		}
		builder.append(getLocation().getLatitude());
		builder.append(",");
		builder.append(getLocation().getLongitude());
		StringBuilder builder2 = new StringBuilder();
		builder2.append(ParserMapResults.BUS_STATION);
		builder2.append("%7C");
		builder2.append(ParserMapResults.SUBWAY_STATION);
		builder2.append("%7C");
		builder2.append(ParserMapResults.TRAIN_STATION);
		Log.e("test", "builder="+builder.toString());
		
		try {
			mapSearchData = mapResults.getSearchResult(builder.toString(),MAX_DISTANCE, true,builder2.toString(),getLanguage());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(mapSearchData==null){
			logE("not find Wineshop");
		}else{
			markOPertorAssistant.startDraw(mapSearchData);
		}
		builder=null;
		builder2=null;
	}

	private String getLanguage(){
		return Config.language==Config.LANGUAGE_EN?ParserMapResults.LANGUAGE_EN:ParserMapResults.LANGUAGE_CN;
	}
	private MarkOperator markOperator = null;


	private void initViews() {
		mMapView = (MapView) findViewById(R.id.track_map);
		mLocationButton = (Button) findViewById(R.id.location_button);
	}
	private void init(){ 
		mLocationOperator = new LocationOperator(this,mMapController);
		markOperator = new MarkOperator(this, mMapController);
		markOPertorAssistant = new MarkOPertorAssistant(markOperator);
	
	}
	private void initEven(){
		mLocationButton.setOnClickListener(mClickListener);
	}
	OnClickListener mClickListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.location_button:
				mLocationOperator.animateTo();
				//openWineshop();
				break;

			default:
				break;
			}
		}
	};
	public static void log(String msg) {
		LogUtils.logD("TAG",msg);
	}

	public static void logE(String msg) {
		LogUtils.logE("TAG",msg);
	}
	public GoogleMapActivity() {
		sMe = this;
	}

	public static GoogleMapActivity getInstance() {
		return sMe;
	}
	
	@Override
	protected void onCreate(Bundle icicle) {
		// TODO Auto-generated method stub
		log("onCreate.");
		super.onCreate(icicle);
		intiDatas();
		setContentView(R.layout.google_map);
		
		initViews();
		mapActivityContor = MapActivityContor.getInstance();
		mMapController = new AbstractGoogleMap(this, mMapView);
		mMapController.init();
		mMapView.setBuiltInZoomControls(true);
		mapResults = new ParserMapResults();
		init();
		initEven();
		
		//openMeetingMap();
		//openFood();
		//PointItemOverlays googleOverlays = new PointItemOverlays(getResources().getDrawable(R.drawable.mark_start_flag),this);
		//mMapView.getOverlays().add(googleOverlays);
		//googleOverlays.addOverlay(new OverlayItemPoint(new GeoPoint((int)(30.6750701847006*1E6),(int)(104.004041925034*1E6)), "", "", googleOverlays));
		
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		log("onDestroy");
		if(loadTask!=null){
			loadTask.cancel(true);
		}
		loadTask=null;
		if(markOperator!=null){
			markOperator.distory();
		}
		markOperator = null;
		if(mMapController!=null){
			mMapController.destroy();
		}
		
		mMapController = null;
		if (mBaiduLocation != null) {
			mBaiduLocation.stopLocation(false);
		}

		GoogleMapService.startService(this,
				GoogleMapService.STOP_LOCATION_LISTENER);
		mMapController = null;
		sMe = null;
		
		
		//mMapController.
		super.onDestroy();
	}  

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		log("onPause");
		super.onPause();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		log("onResume");
		super.onResume();
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		log("onStart");
		super.onStart();
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		log("onStop");
		super.onStop();
	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}
	
	public AbstractMapContorl getMapControler() {
		return mMapController;
	}
	
	private void intiDatas(){
		mBaiduLocation = new BaiduLocation(this.getApplicationContext());
		mBaiduLocation.setCallBack(new IGetLocation() {

			@Override
			public void successful(BDLocation loca) {
				// TODO Auto-generated method stub
				locationChanged(loca, true);
			}

			@Override
			public void overTimeDo() {
				// TODO Auto-generated method stub
				locationChanged(null, false);
			}

			@Override
			public void failure() {
				// TODO Auto-generated method stub
				locationChanged(null, false);
			}
		});
		// showLastLocation();
		if (mBaiduLocation.getLocation() != null) {
			BDLocation location = mBaiduLocation.getLocation();
			Location loc = new Location(LocationManager.GPS_PROVIDER);
			loc.setLatitude(location.getLatitude());
			loc.setLongitude(location.getLongitude());
			loc.setAccuracy(location.getRadius());
			loc.removeAltitude();
			loc.removeBearing();
			loc.removeSpeed();
			mMapController.locationChange(new LocationPoint(loc, location
					.getAddrStr()));
		}
		GoogleMapService.startService(this,
				GoogleMapService.START_LOCATION_LISTENER);
		
		if (mMapController == null) {
			logE("setMapOption->mMapController is null.");
			return;
		}
		mMapController.setSatellite(mMapOption.isSatellite());
		mMapController.setStreetView(mMapOption.isStreetView());
		mMapController.setTraffic(mMapOption.isTraffic());
	}
	/* 
	 * type(FOOD=0;
		 LODGING=1;
	 Traffic=2;
	
	 MEETING=3;)*/
	LoadTask loadTask =null;
	public void openMap(int type){
		switch (type) {
		case DataUtils.FOOD:	
		case DataUtils.LODGING:
		case DataUtils.MEETING:
		case DataUtils.TRAFFIC:
		case DataUtils.TRAVEL:
			mMapController.clearLines();
			mMapController.clearMarks();
			showLoadingDialog();
			status =type;
			loadTask = new LoadTask();
			loadTask.execute();
			
			break;
		default:
			break;
		}
	}
	private class LoadTask extends AsyncTask<Void, Void, Void>{

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			if (GoogleMapActivity.getInstance() != null) {
				switch (status) {
				case DataUtils.FOOD:	
					GoogleMapActivity.getInstance().openFood();		
					break;
				case DataUtils.LODGING:
					GoogleMapActivity.getInstance().openWineshop();
					break;
				case DataUtils.MEETING:
					GoogleMapActivity.getInstance().openMeetingMap();
					
					break;
				case DataUtils.TRAFFIC:
					GoogleMapActivity.getInstance().openTraffic();
					break;
				case DataUtils.TRAVEL:
					GoogleMapActivity.getInstance().openTravel();
					break;
				default:
					break;
				}
				
				
				
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			dismissLoadingDialog();
			mMapController.animateToLocation();
			click = false;
			super.onPostExecute(result);
		
		}
		
	}
	public void dismissLoadingDialog(){
		if(loadingDialog!=null){
			loadingDialog.dismiss();
		}
	}
	public void showLoadingDialog(){
		if(loadingDialog==null)
			loadingDialog = new LoadingDialog(this);
		if(!loadingDialog.isShowing())
			try{
				loadingDialog.show();
			}catch (Exception e) {
				// TODO: handle exception
			}
	}
	public void locationChanged(BDLocation location, boolean isRecorded) {
		log("locationChanged->isRecorded:" + isRecorded + "location:"
				+ location);
		if (location == null) {
			logE("locationChanged->location is null");
			return;
		}
		if (mMapController == null) {
			logE("locationChanged->mMapController is null");
			return;
		}
		Location loc = new Location(LocationManager.GPS_PROVIDER);
		loc.setLatitude(location.getLatitude());
		loc.setLongitude(location.getLongitude());
		loc.setAccuracy(location.getRadius());
		loc.removeAltitude();
		loc.removeBearing();
		loc.removeSpeed();
		// mBaiduLocation.getLocation()
		mMapController.locationChange(new LocationPoint(loc, location
				.getAddrStr()));
		mMapController.deleteLine(1);
		mMapController.addLinePoint(1, loc.getLatitude(), loc.getLongitude());
		mMapController.invalidate();
	}

	public BaiduLocation getBaiduLocation() {
		return mBaiduLocation;
	}

	public Location getLocation() {
		if (mBaiduLocation == null)
			return null;
		BDLocation location = mBaiduLocation.getLocation();
		if (location == null)
			return null;
		Location loc = new Location(LocationManager.GPS_PROVIDER);
		loc.setLatitude(location.getLatitude());
		loc.setLongitude(location.getLongitude());
		loc.setAccuracy(location.getRadius());
		loc.removeAltitude();
		loc.removeBearing();
		loc.removeSpeed();
		return loc;
	}
}
